package com.liang.blog.security.service;

import com.liang.blog.model.constant.CacheConstants;
import com.liang.blog.redis.service.RedisService;
import com.liang.blog.vo.user.LoginUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author：YanWenLiang
 * @Date:2023-08-24-18:19
 */
@Component
public class TokenService {

    @Autowired
    private RedisService redisService;

    /**
     * 刷新登入 token
     * @param loginUserVo
     */
    public void updateToken(LoginUserVo loginUserVo){
        // 设置登入时间
        loginUserVo.setLoginTime(System.currentTimeMillis());

        // 设置过期时间
        loginUserVo.setExpireTime(loginUserVo.getLoginTime() +
                CacheConstants.EXPIRATION * 60 * 1000);

        redisService.setCacheObject(getTokenKey(loginUserVo.getToken()),
                loginUserVo, CacheConstants.EXPIRATION, TimeUnit.MINUTES);
    }

    /**
     * 验证令牌有效期，相差不足120分钟，自动刷新缓存
     *
     * @param loginUser
     */
    public void verifyToken(LoginUserVo loginUser) {
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= CacheConstants.REFRESH_TIME * 1000 * 60) {
            updateToken(loginUser);
        }
    }

    public String getTokenKey(String token){
        return CacheConstants.LOGIN_TOKEN_KEY + token;
    }
}
